<template>
  <div class="cropper-wrapper">
    <div class="img-box bg">
      <img class="cropper-image" :id="imgId" alt />
    </div>
    <div class="right-con">
      <div v-if="preview" class="preview-box bg" :id="previewId"></div>
      <div class="button-box">
        <slot>
          <el-upload
            name="file"
            :action="uploadUrl"
            :on-success="success"
            :on-error="handleError"
            :data="data"
            :before-upload="beforeUpload"
            :headers="headers"
            accept="image/*"
          >
            <el-button style="width: 150px;" type="primary">{{insideSrc?'重新上传':'上传图片'}}</el-button>
          </el-upload>
        </slot>
        <div v-show="insideSrc">
          <el-button
            style="width: 150px;margin-top: 10px;"
            type="primary"
            :disabled="!uploadSuccess"
            @click="crop"
          >{{ cropButtonText }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.min.css";
import { getToken } from "@/utils/auth";
import axios from 'axios'

export default {
  name: "Cropper",
  props: {
    src: {
      type: String,
      default: ""
    },
    preview: {
      type: Boolean,
      default: true
    },
    moveStep: {
      type: Number,
      default: 4
    },
    cropButtonText: {
      type: String,
      default: "确认上传"
    },
    maxSize: {
      type: Number,
      default: 2048*1024
    },
    width: {
      type: Number,
      default: 347
    },
    height: {
      type: Number,
      default: 138
    },
    id: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      cropper: null,
      insideSrc: "",
      uploadUrl: "",
      imgurl: "",
      uploadSuccess: false,
      data: {},
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      host: '',
      dir: ''
    };
  },
  computed: {
    imgId() {
      return `cropper${this.id}`;
    },
    previewId() {
      return `cropper_preview${this.id}`;
    }
  },
  watch: {
    src(src) {
      this.replace(src.split("?")[0]);
      if (src != "") {
        this.uploadSuccess = true;
        this.imgurl = src.split("?")[0];
      }
    },
    insideSrc(src) {
      this.replace(src);
    }
  },
  methods: {
    beforeUpload(file) {
      if(file.size>this.maxSize){
        this.$message({
          message: "上传文件过大,请上传小于" + this.maxSize / 1024 + "M的文件",
          type: 'warning'
        });
        return
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);

      reader.onload = event => {
        this.insideSrc = event.srcElement.result;
      };
      this.data.key = this.dir + '.' + file.uid
    },
    replace(src) {
      this.cropper.replace(src);
      this.insideSrc = src;
    },
    rotate() {
      this.cropper.rotate(90);
    },
    shrink() {
      this.cropper.zoom(-0.1);
    },
    magnify() {
      this.cropper.zoom(0.1);
    },
    scale(d) {
      this.cropper[`scale${d}`](-this.cropper.getData()[`scale${d}`]);
    },
    move(...argu) {
      this.cropper.move(...argu);
    },
    crop() {
      let a = this.cropper.getData(true);

      var url = `${this.imgurl}?x-oss-process=image/crop,x_${a.x},y_${a.y},w_${a.width},h_${a.height}`;

      this.$emit("on-crop", url);
    },
    success(r, file) {
      this.uploadSuccess = true;
      this.imgurl = this.host + '/' + this.data.key;
    },
    handleError: function(e) {
      this.$message({
        type: 'warning',
        message: "上传失败,请重试"
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      axios.get("https://api.mdc.movecloud.cn/api/oss-signature?objname=alphajiushikart").then((res)=>{
        if(res.status*1==200){
          this.uploadUrl = res.data.data.host
          this.data = {
            signature: res.data.data.signature,
            ossAccessKeyId: res.data.data.accessid,
            policy: res.data.data.policy,
            key: res.data.data.dir+res.data.sys_time
          }
          this.host = res.data.data.host
          this.dir = res.data.data.dir+res.data.sys_time
        }
      })
      let dom = document.getElementById(this.imgId);
      this.cropper = new Cropper(dom, {
        preview: `#${this.previewId}`,
        checkCrossOrigin: true,
        // aspectRatio: this.width / this.height,
        viewMode: 1,
        checkCrossOrigin: false
      });
    });
  }
};
</script>
<style>
.bg{
  background-image: url("")
}
.cropper-wrapper{
  width: 100%;
  height: 340px;
}
.img-box{
    height: 340px;
    width: 530px;
    border: 1px solid #ebebeb;
    display: inline-block;
}
img{
  max-width: 100%;
  display: block;
}
  
.right-con{
  display: inline-block;
  width: 170px;
  vertical-align: top;
  box-sizing: border-box;
  padding: 0 10px;
  
}

.preview-box{
  height: 60px;
  width: 100%;
  overflow: hidden;
  border: 1px solid #ebebeb;    
}
.button-box{
  padding: 10px 0 0;
}


</style>